import { View, Button, Text, Input } from "@tarojs/components";
import { useState } from "react";
import Taro from "@tarojs/taro";
import { useRoomService } from "../../hooks/useRoomService";

import "./index.less";

export default function Home() {
  const [roomId, setRoomId] = useState<string>('');
  const { createRoom } = useRoomService({ roomId: '' });

  const handleCreateRoom = async () => {
    try {
      const result = await createRoom();
      if (result.success && result.roomId) {
        // 创建房间成功，跳转到room页面
        Taro.navigateTo({
          url: `/pages/room/index?roomId=${result.roomId}`
        });
      }
    } catch (error) {
      console.error("创建房间失败:", error);
      Taro.showToast({ title: "创建房间失败", icon: "none" });
    }
  };

  const handleJoinRoom = () => {
    if (roomId.trim()) {
      // 跳转到room页面
      Taro.navigateTo({
        url: `/pages/room/index?roomId=${roomId}`
      });
    } else {
      Taro.showToast({ title: "请输入房间号", icon: "none" });
    }
  };

  return (
    <View className='home-container'>
      <View className='game-icon'></View>
      <Text className='title'>欢迎来到游戏</Text>
      
      <View className='room-input-container'>
        <Input
          className='room-input'
          placeholder='请输入房间号'
          value={roomId}
          onInput={(e) => setRoomId(e.detail.value)}
        />
        <Button className='join-room-btn' onClick={handleJoinRoom}>
          加入房间
        </Button>
      </View>
      
      <Button className='create-room-btn' onClick={handleCreateRoom}>
        创建房间
      </Button>
      
      <Text className='footer-text'>与朋友一起享受游戏的乐趣</Text>
    </View>
  );
}